<?php
/**
 * 《材料信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Material.class.php 1059 2010-04-08 07:55:21Z sunxy $
 */
require_once(dirname(__FILE__) . '/MaterialUtil.class.php');

class Material extends MaterialUtil {
	public $tbl = Constant::tbl_material;

	var $info_dir = 'material';

	public $status = array(
		'-' => '请选择',
		'1' => '正常',
		'2' => '暂停',
		'3' => '停止',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'code' => '编号',
		'name' => '名称',
		'standard' => '规格',
		'price' => '单价',
	
		// 'tj1' => '次数',
		'tj2' => '金额',	
		
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'category' => '大类',
		'subclass' => '小类',
		'emp' => '负责人',
		'status' => '状态',
	
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('category_option', $this->_category());
	}
	
	function mobile($controller, $request) {
		$this->pretreat($controller);
	
		global $CategoryTree;
	
		$data = $CategoryTree['物料管理'];
	
		$ret = array();
		foreach ($data as $k => $v) {
			if ($this->tree_my($v)) {
				$ret[$k] = $v;
			}
		}
	
		$controller->assign('menu', $ret);
	
		$controller->display($request, 'mobile');
		return true;
	}
	
	function tab($controller, $request) {		
		$data = array(
			'物料需求' => array('cc'=>'material.php?do=BomMy.find', 'js'=>''),
			'材料信息' => array('cc'=>'material.php?do=Material.find', 'js'=>''),			
			'材料图片' => array('cc'=>'material.php?do=Pic.find', 'js'=>''),
		
			'物料库存' => array('cc'=>'material.php?do=Amount.find', 'js'=>''),
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tab');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '负责人',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'material/material/find');
		return true;
	}

	function _category() {
		$key = "material.category_";
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT DISTINCT category FROM %s WHERE length(category) > 0";
		$sql = sprintf($fmt, $this->tbl);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array('-'=>'请选择');
		while ($row = $db->fetch_array($result)) {
			$ret[$row['category']] = $row['category'];
		}

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	function _subclass() {
		$key = "material.subclass_";
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT DISTINCT subclass FROM %s WHERE length(subclass) > 0";
		$sql = sprintf($fmt, $this->tbl);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array('-'=>'请选择');
		while ($row = $db->fetch_array($result)) {
			$ret[$row['subclass']] = $row['subclass'];
		}

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_category($controller, $request) {
		if (!empty($request['category'])) {
			$category = $request['category'];
		}

		if (!empty($request['category_s'])) {
			$category = $request['category_s'];
		}

		if (!empty($request['category_t'])) {
			$category = $request['category_t'];
		}

		if (empty($category) || $category == '-') {
			$data[] = array('code'=>'-', 'name'=>'请选择');
			echo json_encode($data);
			return false;
		}

		$key = "material.category_" . substr(md5($category), 0, 10);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				echo json_encode($ret);
				return true;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT DISTINCT subclass FROM %s WHERE category = '%s'";
		$sql = sprintf($fmt, $this->tbl, $category);
		debug($sql);
		$result = $db->query($sql);
		$ret[] = array('code'=>'-', 'name'=>'请选择');
		while ($row = $db->fetch_array($result)) {
			$row['code'] = $row['subclass'];
			$row['name'] = $row['subclass'];

			$ret[] = $row;
		}

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 hour"));
		}

		echo json_encode($ret);
		return true;
	}

	/**
	 * 清除缓存
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_category_subclass($controller, $request) {
		$category = $this->_category();
		while (list($k, $v) = each($category)) {
			$key = "material.category_" . substr(md5($k), 0, 10);
			clean($key);
		}

		$key = "material.category_";
		clean($key);

		$key = "material.subclass_";
		clean($key);

		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == '`join`') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['join'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$code_s = $this->_input($request['code_s']);
		$name_s = addslashes(trim($request['name_s']));

		$category_s = $request['category_s'];
		$subclass_s = $request['subclass_s'];

		$where = " WHERE 1=1";

		if (!empty($code_s)) {
			$where .= " AND code = '" . $code_s . "'";
		}

		if (!empty($name_s)) {
			$where .= " AND (name LIKE '%" . $name_s . "%' OR standard LIKE '%" . $name_s . "%' OR content LIKE '%" . $name_s . "%')";
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND category = '" . $category_s . "'";
		}

		if (!empty($subclass_s) && $subclass_s <> '-') {
			$where .= " AND subclass = '" . $subclass_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'material/material/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function xls($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/material/list');
		return true;
	}

	function _pic1($material) {
		$db = newdb(Constant::tbl_contact);
		$fmt = "SELECT * FROM %s WHERE material = '%s' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_material_pic, $material);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return Download::url($this->info_dir, $row['createtime'], $row['material'], $row['name']);
		}

		return '/images/none.gif';
	}

	function _pic2($id) {
		$db = newdb(Constant::tbl_contact);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, Constant::tbl_material_pic, $id);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return Download::url($this->info_dir, $row['createtime'], $row['material'], $row['name']);
		}

		return '/images/none.gif';
	}

	function _pic_my($material, $id) {
		$db = newdb(Constant::tbl_contact);
		$fmt = "SELECT * FROM %s WHERE material = '%s' ORDER BY orderby";
		$sql = sprintf($fmt, Constant::tbl_material_pic, $material);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['file'] = Download::url($this->info_dir, $row['createtime'], $row['material'], $row['name']);

			$ret[] = $row;
		}

		return '/images/none.gif';
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'material/material/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$name = addslashes($request['name']);

		$zjm = getPinyin($name);
		$zjm = strtoupper($zjm);

		$category = addslashes($request['category']);
		$subclass = addslashes($request['subclass']);

		$standard = addslashes($request['standard']);
		$density = $request['density'];

		$unit = $request['unit'];
		$price = $request['price'];
		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(name, zjm, category, subclass, standard, density, unit, price, content, emp, oper";
		$fmt .= ", createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $name, $zjm, $category, $subclass, $standard, $density, $unit, $price, $content, $emp, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _code($subclass, $id) {
		$zjm = getPinyin($subclass);
		$zjm = strtoupper($zjm);
			
		$ret = substr($zjm, 0, 2) . sprintf("%04d", $id);
			
		return $ret;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/material/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$code = $request['code'];

		$name = $request['name'];
		$zjm = getPinyin($name);
		$zjm = strtoupper($zjm);

		$category = addslashes($request['category']);
		$subclass = addslashes($request['subclass']);

		$standard = $request['standard'];
		$density = $request['density'];

		$unit = $request['unit'];
		$price = $request['price'];
		// $content = sprintf("%s\n%s 修改", addslashes($request['content']), Name::emp($_SESSION['id']));
		$content = addslashes($request['content']);

		$status = $request['status'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET code = '%s', name = '%s', zjm = '%s', category = '%s', subclass = '%s', standard = '%s', density = '%s', unit = '%s', price = '%s'";
		$fmt .= ", content = '%s', emp = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code, $name, $zjm, $category, $subclass, $standard, $density, $unit, $price, $content, $emp, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}

		if (empty($code)) {
			$code = $this->_code($subclass, $id);
		}

		$fmt = "UPDATE %s SET code = '%s' WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code, $id);
		// debug($sql);
		$db->query($sql);
			
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/material/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$controller->display($request, 'material/material/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}

		$row['file'] = $this->_pic1($id);

		$row = $this->_view_t($row);

		return $row;
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
	
			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}
	
			$this->_delete3($id);
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2 WHERE id = '%s'";
		}
	
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}
	
		$emp = $_SESSION['id'];
	
		if ($row['emp'] == $emp) {
			return true;
		}
	
		if ($row['oper'] == $emp) {
			return true;
		}
	
		return false;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function pic($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('material', $row);

		$this->_pic($controller, $row);

		$controller->display($request, 'material/material/pic');
		return true;
	}

	function _pic($controller, $data) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE material = '%s' ORDER BY orderby DESC";
		$sql = sprintf($fmt, Constant::tbl_material_pic, $data['id']);
		$result = $db->query($sql);

		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['file'] = Download::url($this->info_dir, $row['createtime'], $row['material'], $row['name']);
			$row['size_t'] = printsize($row['size']);

			$ret[] = $row;
		}

		$controller->assign_by_ref('pic', $ret);
	}

	function ajax_upload($controller, $request) {
		$s = print_r($request, true);
		debug($s);

		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			die($file->getMessage());
		}

		if ($file->isValid()) {
			$now = date('Y-m-d H:i:s');

			$id = $request['id'];
			$name = $request['name'];
			if (empty($name) || $name == '-') {
				$name = 'uniq';
			}

			$dir = Download::dir($this->info_dir, $now, $id);
			debug($dir);
			if (!@file_exists($dir)) {
				umask();
				mkdir($dir, 0777, true);
			}

			$file->setName($name);
			$filename = $file->moveTo($dir);
			if (PEAR::isError($filename)){
				die($filename->getMessage());
			}

			$filesize = $file->upload['size'];

			$db = newdb($this->dsn);
			$fmt = "INSERT INTO %s(material, name, size, createtime)";
			$fmt .= " VALUES('%s', '%s', '%s', now())";
			$sql = sprintf($fmt, Constant::tbl_material_pic, $id, $filename, $filesize);
			debug($sql);
			$db->query($sql);
		}

		echo "1";
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function picPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$code = $request['code'];

		$name = $request['name'];

		$category = addslashes($request['category']);
		$type = addslashes($request['type']);

		$standard = $request['standard'];
		$unit = $request['unit'];
		$price = $request['price'];
		$content = $request['content'];

		$status = $request['status'];

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET code = '%s', name = '%s', category = '%s', type = '%s', standard = '%s', unit = '%s', price = '%s', content = '%s'";
		$fmt .= ", status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code, $name, $category, $type, $standard, $unit, $price, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}
			
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		$controller->assign('t1', strtotime('-1 month'));
		$controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'material/material/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'category');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function _name($row, $px) {
		$row = $this->_name_t($row, $px);

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_code($controller, $request) {
		
		$data = $this->_ajax_code($request);
		echo json_encode($data);
	}

	function _ajax_code($request) {
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
		
		$key = sprintf("%s_code_%s", $this->tbl, $q);
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE (zjm LIKE '%s' OR code LIKE '%s') ORDER BY id DESC LIMIT %s";
		$sql = sprintf($fmt, $this->tbl, "%" . $q . "%", $q . "%", $n);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$ret[] = $row;
		}

		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 hour"));
		}

		return $ret;
	}
	
	function ajax_zjm($controller, $request) {
	
		$data = $this->_ajax_zjm($request);
		echo json_encode($data);
	}
	
	function _ajax_zjm($request) {
		$q = strtolower($request['q']);
	
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
	
		if (preg_match("/^(\d+)(.+)/", $q, $m)) {
			$status = $m[1];
			$zjm = $m[2];
		} else {
			$status = 1;
			$zjm = $q;
		}
	
		if (empty($zjm)) {
			debug("OK" . $zjm);
			return array();
		}
	
		// $key = $this->prefix . "ajax_zjm_" . $q;
		if ($status == 1) {
			$key = sprintf("%s_%s_%s_%s", $this->zjm, $this->tbl, $this->prefix, $zjm);
		} else {
			$key = sprintf("%s_%s_%s_%s_%s", $this->zjm, $this->tbl, $this->prefix, $status, $zjm);
		}
	
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}
	
		$db = newdb($this->dsn_r);
		if ($status == '1') {
			$fmt = "SELECT *, length(zjm) c FROM %s WHERE visible = 1 AND status IN ('1', '9') AND zjm LIKE '%s' ORDER BY c, id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, "%" . $zjm . "%", $n);
		} else {
			$fmt = "SELECT *, length(zjm) c FROM %s WHERE visible = 1 AND status = '%s' AND zjm LIKE '%s' ORDER BY c, id DESC LIMIT %s";
			$sql = sprintf($fmt, $this->tbl, $status, "%" . $zjm . "%", $n);
		}
	
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
	
			$ret[] = $row;
		}
	
		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}
	
		return $ret;
	}

	function ajax_id($controller, $request) {
		$id = $this->_input($request['id']);
		$data = $this->_ajax_id($id);
		debug(print_r($data, true));
		echo json_encode($data);
	}

	function _ajax_id($id) {
		if (!preg_match("/^(\d+)$/i", $id)) {
			return array();
		}

		$key = "material.ajax_id_" . $id;
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id = '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			return array();
		}

		$ret = $db->fetch_array($result);
		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 hour"));
		}

		return $ret;
	}
	
	function z($controller, $request) {
		$db = newdb($this->dsn_w);

		$aa = array('钢材'=>'产品钢材', 
		'产品加工材料'=>'产品配件',
		'其他'=>'其它', 
		);

		while (list($k, $v) = each($aa)) {
			$fmt = "UPDATE %s SET category = '%s' WHERE category = '%s'";
			$sql = sprintf($fmt, $this->tbl, $v, $k);
			echo $sql . "\n";
			$db->query($sql);
		}

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}

	function u($controller, $request) {
		$db = newdb($this->dsn);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$zjm = getPinyin($row['subclass']);
			$zjm = strtoupper($zjm);

			$code = substr($zjm, 0, 2) . sprintf("%04d", $row['id']);

			$fmt = "UPDATE %s SET code = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $code, $row['id']);
			debug($sql);
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}

	function sync_category($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s a, %s b set b.category = a.category, b.subclass = a.subclass WHERE b.material = a.id";
		// $fmt = "UPDATE %s a, %s b set b.category = a.category, b.subclass = a.subclass WHERE a.name = b.name and a.standard = b.standard";
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_material_amount);
		echo $sql . "\n";
		$db->query($sql);
		
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_material_bom);
		echo $sql . "\n";
		$db->query($sql);
		
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_material_bom);
		echo $sql . "\n";
		$db->query($sql);
		
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_wl_in);
		echo $sql . "\n";
		$db->query($sql);
		
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_wl_out);
		echo $sql . "\n";
		$db->query($sql);
		
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_wl_record_in);
		echo $sql . "\n";
		$db->query($sql);
		
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_wl_record_out);
		echo $sql . "\n";
		$db->query($sql);

		logdate($controller, $request);
		return true;
	}

	function t1($controller, $request) {
		echo $this->_code("ab", "233");

		logdate($controller, $request);
		return true;
	}
	
	function _update_price($id, $price) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET price = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $price, $id);
		$db->query($sql);
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('122');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			// echo "222";
			return false;
		}

		$from = $this->email;
		$subject = '材料信息';
		
		$cc = array(	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'id DESC'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'id DESC'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}

		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'material/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function tjw($controller, $request) {
		$bb = $this->_list_email('122');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$this->pretreat($controller);

		$from = $this->email;
		$subject = '材料信息（周报）';
		
		$cc = array(	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'id DESC'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'id DESC'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE modifytime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'material/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
		
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'emp';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, COUNT(id) AS c FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, COUNT(id) AS c FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function _update_tj1($id, $s) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET tj1 = '%s' WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $s, $id);
		echo $sql . "\n";
		$db->query($sql);
	}
	
	function _update_tj2($id, $s) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET tj2 = '%s' WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $s, $id);
		echo $sql . "\n";
		$db->query($sql);
	}
}
?>